<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
    @close="jkeModalUpdate"
  >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['首页']" currentMenu="申请采购"></crumbs>
    <div class="form-body">
      <a-card title="基本信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="使用日期">
            <a-date-picker
              valueFormat="YYYY-MM-DD"
              v-decorator="['useDate', { rules: [{ required: true, message: '请选择' }] }]"
            />
          </a-form-item>
        </a-form>
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="采购事由" style="width: 65%">
            <a-textarea
              placeholder="请输入"
              auto-size
              v-decorator="['reason', { rules: [{ required: true, message: '请输入采购事由' }] }]"
            />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card title="采购明细" :bordered="false" style="margin-top: 12px; height: 345px">
        <a-col :span="24" style="margin-bottom: 38px">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="applyBuy.loading"
            :rowNumber="true"
            :columns="applyBuy.columns"
            :dataSource="applyBuy.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :actionButton="true"
            @valueChange="valueChange"
          >
            <template v-slot:picUrl="props">
              <img v-if="props.value !== ''" :src="props.value" alt="" class="imgClass" />
              <img v-else :src="pictureUrl" alt="" class="imgClass" />
            </template>
            <template v-slot:goodsName="props">
              <!-- <a-select
                placeholder="请选择"
                allowClear
                showSearch
                style="width: 100%"
                :not-found-content="goodsBaseInfo.length > 0 ? null : '暂无数据'"
                :filter-option="filterOption"
                @select="(bl, e) => onChangeSelect(bl, props)"
                :defaultValue="props.value"
              >
                <a-select-option v-for="(item, key) in goodsBaseInfo" :key="key" :value="item.id">{{
                  item.goodsName
                }}</a-select-option>
              </a-select> -->
              <a-input @click="openItGoods(props)" :value="props.value" placeholder="请选择" :class="props.value?'has-value':''" :read-only="true">
                <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
                <a-icon slot="suffix" type="close-circle" theme="filled" class="close-icon" @click="getSelectValue(false, '', [], props.rowId)" />
              </a-input>
            </template>
            <template v-slot:action="props">
              <a-popconfirm
                title="是否删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDeleteS(props)"
                @cancel="cancel"
              >
                <a style="padding-left: 3px; color: #f25643">删除</a>
              </a-popconfirm>
            </template>
          </j-editable-table>
        </a-col>
      </a-card>
      <div style="margin-top: 12px">
        <Examine @submitProcess="submitProcess" type="0" id="ERP_PURCHASE_TASK_APPLY" ref="examine" />
        <div style="height: 50px"></div>
      </div>
    </div>
    <div class="footer-submit form-footer">
      <a-button @click="goBack" class="submitBtn" style="margin-right: 10px"> 取消 </a-button>
      <a-button type="primary" class="submitBtn" :loading="loadingSubmit" @click="submitProcess"> 提交 </a-button>
    </div>
    <goodsTableSelect ref="goodsTableSelect" @getSelectValue="getSelectValue" :key="indexGoods"> </goodsTableSelect>
  </jke-modal>
</template>
<script>
import {
  VALIDATE_NO_PASSED,
  FormTypes,
  getRefPromise,
  validateFormAndTables,
  validateTables,
} from '@/utils/JEditableTableUtil'
import crumbs from '@/components/crumbs.vue'
import { APILX } from '@/api/requestLx'
import { API } from '@/api/requestFzs'
import { getFileListByIds } from '@/api/api'
import { apiBaseUrlDownload } from '@/utils/request'
import goodsTableSelect from '@/components/goodsTableSelect'
import Examine from '@/components/examine'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { fourFloatNum } from '@/utils/util'
import { getAllGoodsBaseInfo } from '@/api/goodsManagement'
export default {
  name: 'applyPay', //申请付款
  data() {
    return {
      jkeForm: {
        title: '申请采购',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      //下拉改弹窗
      indexGoods: 0,
      goodsRowId: '',
      columns: [
        {
          title: '物品编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsCode',
          searchKey: 'goodsCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsCode',
          },
        },
        {
          title: '物品名称',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsName',
          searchKey: 'goodsName',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsName',
          },
        },
        {
          title: '规格',
          width: 100,
          ellipsis: true,
          dataIndex: 'spec',
          searchKey: 'spec',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'spec',
          },
        },
        {
          title: '物品类型',
          width: 100,
          ellipsis: true,
          dataIndex: 'typeText',
          searchKey: 'type',
          type: 'select',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'typeText',
          },
        },
        {
          title: '物品分类',
          width: 100,
          ellipsis: true,
          dataIndex: 'categoryText',
          searchKey: 'category',
          type: 'tree',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'categoryText',
          },
        },
      ],
      goodsValue: '',
      goodsText: '',
      filterForm: {
        goodsCode: '', //物品编号
        goodsName: '', //物品名称
      },
      //下拉改弹窗结束
      domianURL: apiBaseUrlDownload, //表格图片展示
      pictureUrl: require('../../assets/img/noPicture.jpg'),
      picNowUrl: '',
      goodsBaseInfo: [], //物品下拉
      loadingSubmit: false, //防止多次提交
      form: this.$form.createForm(this, { name: 'coordinated' }),
      attachment: '',
      // 采购明细
      refKeys: ['applyBuy'],
      tableKeys: ['applyBuy'],
      processList: [], //表格-工序 数据
      applyBuy: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '',
            key: 'goodsId',
            align: 'center',
            width: '0%',
            disabled: true,
          },
          {
            title: '图片',
            key: 'picUrl',
            type: FormTypes.slot,
            slotName: 'picUrl',
          },
          {
            title: '物品编号',
            key: 'goodsCode',
            type: FormTypes.input,
            placeholder: '请输入',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '物品名称',
            isrequired: true,
            // width: '10%',
            key: 'goodsName',
            validateRules: [{ required: true, message: '${title}不能为空' }],
            type: FormTypes.slot,
            slotName: 'goodsName',
          },
          {
            title: '规格',
            key: 'spec',
            type: FormTypes.input,
            placeholder: '请输入',
            disabled: true,
            defaultValue: '',
          },
          {
            title: '本次采购数量',
            key: 'num',
            isrequired: true,
            type: FormTypes.input,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [
              { required: true, message: '${title}不能为空' },
              {
                pattern: /[1-9]+[0-9]*/,
                message: '${title}不能为空且为大于0的数字',
              },
            ],
          },
          {
            title: '操作',
            width: '20%',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
    }
  },
  components: {
    FileUpload,
    crumbs,
    goodsTableSelect,
    Examine,
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
  },
  methods: {
    jkeModalUpdate() {
      if (this.$route.path == '/dashboard/analysis') {
        this.$store.commit('SET_CURRENT_PREFIX','/jksaas-mgt/mgt')
      }
    },
    initForm() {
      this.$store.commit('SET_CURRENT_PREFIX','/jksaas-produce/produce')
      this.jkeForm.visible = true
      this.getDictModel()
    },
    searchResetGoods() {
      this.filterForm.goodsCode = ''
      this.filterForm.goodsName = ''
      this.$refs.goodsTableSelect.searchReset()
    },
    searchGoods() {
      this.$refs.goodsTableSelect.searchQuery(this.filterForm)
    },
    // 物料下拉改弹窗
    openItGoods(props) {
      this.goodsRowId = props.rowId
      let par = {
        list: '/wms/goods/getAllGoodsBaseInfo',
        visible: true, //弹窗开启
        title: '物料', //标题名称
        multi: false, //是否多选
        columns: this.columns, //表格配置
        value: this.goodsValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.goodsText, //回显的中文，如：'张三'
        textKey: 'goodsName', //回显的中文key
      }
      this.$refs.goodsTableSelect.getInit(par)
    },
    getSelectValue(id, text, item, rowId) {
      if (!id) {
        this.$refs.applyBuy.setValues([
          {
            rowKey: rowId, // 行的id
            values: {
              goodsId: '',
              goodsCode: '',
              goodsName: '',
              spec: '',
              picUrl: '',
            },
          },
        ])
        this.goodsText = ''
        this.goodsValue = ''
        return
      }
      this.indexGoods += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.goodsValue = id
      this.goodsText = text
      console.log(id, text, item, '列表选择的数据')
      this.onChangeSelect(id, item)
    },
    // jeecg table选物品 change
    onChangeSelect(bl, props) {
      console.log(bl, props)
      let goodsItem = this.goodsBaseInfo.filter((node) => node.id == bl)
      console.log(goodsItem, 'goodsItem.0')

      if (goodsItem[0].attachment) {
        let ids = goodsItem[0].attachment
        getFileListByIds({ ids }).then((res) => {
          if (res.code == 200) {
            let fileList = ''
            fileList = res.result
            if (fileList.length > 0) {
              this.picNowUrl = this.domianURL + fileList[0].uri
              this.$refs.applyBuy.setValues([
                {
                  rowKey: this.goodsRowId, // 行的id
                  values: {
                    picUrl: this.domianURL + fileList[0].uri,
                  },
                },
              ])
            } else {
              this.picNowUrl = require('../../assets/img/noPicture.jpg')
              this.$refs.applyBuy.setValues([
                {
                  rowKey: this.goodsRowId, // 行的id
                  values: {
                    picUrl: require('../../assets/img/noPicture.jpg'),
                  },
                },
              ])
            }
          }
        })
      }
      this.$refs.applyBuy.setValues([
        {
          rowKey: this.goodsRowId, // 行的id
          values: {
            goodsId: bl,
            goodsCode: goodsItem[0].goodsCode,
            goodsName: goodsItem[0].goodsName,
            spec: goodsItem[0].spec,
          },
        },
      ])
      const { error, values } = this.$refs.applyBuy.getValuesSync({ validate: true })
      console.log(values, 'valuesvalues')
      // 校验物品唯一
      let idLength = 0
      values.forEach((item) => {
        if (item.goodsId == bl) {
          idLength++
        }
      })
      if (idLength == 2) {
        this.$antdMessage.error('该物品已存在')
        this.$refs.applyBuy.removeRows(props.rowId)
        this.$refs.applyBuy.setValues([
          {
            rowKey: props.rowId, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              picUrl: '',
              goodsId: '',
              goodsCode: '',
              goodsName: '',
              spec: '',
            },
          },
        ])
      }
    },
    // 下拉搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    valueChange(type) {
      // console.log(type, 'value change type')
      // debugger
      if (type.column.key == 'num') {
        if (type.value) {
          this.$refs.applyBuy.setValues([
            {
              rowKey: type.row.id, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                num: fourFloatNum(type.value),
              },
            },
          ])
        }
      }
    },
    // 下拉搜索
    filterOption(input, option) {
      console.log('inputoption', input, option)
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    getDictModel() {
      getAllGoodsBaseInfo({ pageSize: 999, pageNo: 1 }).then((res) => {
        this.goodsBaseInfo = res.result.records
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeModalUpdate()
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      // console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (e.nodeDtos) {
        // 获取到数据后写表单提交的方法
        this.saveForm(e)
      } else {
        // 调用子组件的方法获取数据
        this.$refs.examine.confirm()
      }
    },
    // 提交
    saveForm(processDataVo) {
      const { error, values } = this.$refs.applyBuy.getValuesSync({ validate: true })
      console.log(values, 'values save')
      if (!error) {
        if (values.length > 0) {
          let pValue = values
          this.handleSubmit(pValue, processDataVo)
        } else {
          this.$antdMessage.error('采购明细不能为空')
        }
      }
    },
    handleSubmit(pValue, processDataVo) {
      console.log(pValue, processDataVo, 'pValue, sValue')
      this.form.validateFields((err, values) => {
        if (!err) {
          let parameters = {
            ...values,
            attachment: this.attachment,
            erpPurchaseTaskApplyItemDto: pValue,
            processDataVo: processDataVo,
          }
          console.log(parameters, 'parameters')
          this.loadingSubmit = true
          APILX.erpPurchaseTaskApplyAdd(parameters).then((res) => {
            if (res.code == 200) {
              this.loadingSubmit = false
              let subMsg = '申请采购成功'
              this.$antdMessage.success(subMsg)
              this.$emit('refresh')
              this.goBack()
            } else {
              this.loadingSubmit = false
              this.$antdMessage.error(res.message)
            }
          })
        }
      })
    },
    cancel() {},
    // 采购-删除
    handleDeleteS(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
    },
    cancelS() {},
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
/deep/.ant-form-vertical {
  display: flex;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 70px);
  overflow-y: scroll;
}
.form-footer {
  position: absolute;
  left: 0;
  bottom: 0;
}
.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
.imgClass {
  width: 100px;
  height: 80px;
  border-radius: 6px;
  padding: 10px 0;
}
/deep/.td > span {
  position: relative;
  left: -11px;
}
</style>
